package rexsee.core.browser;

import rexsee.core.browser.clazz.JavascriptInterface;
import rexsee.core.browser.clazz.PreloadFilterListener;
import rexsee.core.utilities.Utilities;

public class RexseePreload implements JavascriptInterface {

	public static final String INTERFACE_NAME = "Preload";
	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return new RexseePregFilter(childBrowser);
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return new RexseePregFilter(childBrowser);
	}

	public final static int MAX_PRELOAD = 10;
	private final Browser mBrowser;
	private final PreloadFilterListener listener;

	public RexseePreload(Browser browser) {
		mBrowser = browser;
		listener = new PreloadFilterListener();
		browser.urlListeners.addFilter(listener);
	}

	//JavaScript Interface
	public void preloadCurrent() {
		String url = mBrowser.history.getCurrentItem().getUrl();
		if (contains(url)) return;
		if (mBrowser.source != null) {
			while (listener.getNumberOfUrls() > MAX_PRELOAD) {
				listener.removeFirst();
			}
			listener.add(url, mBrowser.source);
		}
	}
	public void preload(String theUrl) {
		final String url = mBrowser.urlListeners.getAbsoluteUrl(theUrl);
		if (contains(url)) return;
		while (listener.getNumberOfUrls() > MAX_PRELOAD) {
			listener.removeFirst();
		}
		new Thread() {
			@Override
			public void run() {
				String code = Utilities.getContent(mBrowser.getContext(), url, null);
				if (code != null) listener.add(url, code);
			}
		}.start();
	}
	public int size() {
		return listener.getNumberOfUrls();
	}
	public boolean contains(String url) {
		url = mBrowser.urlListeners.getAbsoluteUrl(url);
		return listener.containsUrl(url);
	}
	public void remove(String url) {
		url = mBrowser.urlListeners.getAbsoluteUrl(url);
		listener.remove(url);
	}
	public void remove() {
		listener.remove();
	}
	public String get() {
		return listener.getUrls();
	}
	public String getCode(String url) {
		url = mBrowser.urlListeners.getAbsoluteUrl(url);
		String rtn = listener.getCode(url);
		return (rtn == null) ? "" : rtn;
	}

}
